'use client'

import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Filter, ChevronDown, ChevronUp } from 'lucide-react'

interface DataSourceFilterProps {
  currentFilter: string
  onFilterChange: (filter: string) => void
  parameters: Array<{ data_source: string }>
  className?: string
}

const DATA_SOURCE_OPTIONS = [
  { value: 'all', label: '全部字段', description: '显示所有字段', color: 'bg-gray-100' },
  { value: 'P', label: '采购数据', description: '由采购部门提供的设备参数', color: 'bg-blue-100' },
  { value: 'E', label: '设计数据', description: '由设计部门确定的参数', color: 'bg-green-100' },
  { value: 'M', label: '监测数据', description: '由监测设备和系统提供的参数', color: 'bg-orange-100' },
  { value: 'C', label: '施工数据', description: '由施工部门记录的参数', color: 'bg-yellow-100' },
  { value: 'O', label: '建设数据', description: '由建设部门记录的参数', color: 'bg-purple-100' },
  { value: 'R', label: '运维数据', description: '由运维部门记录的参数', color: 'bg-pink-100' }
]

export default function DataSourceFilter({
  currentFilter,
  onFilterChange,
  parameters,
  className = ''
}: DataSourceFilterProps) {
  const [showDetails, setShowDetails] = useState(false)

  // 计算各数据来源的统计信息
  const getDataSourceStats = () => {
    const stats: Record<string, number> = {}
    parameters.forEach(param => {
      const source = param.data_source || 'unknown'
      stats[source] = (stats[source] || 0) + 1
    })
    return stats
  }

  const dataSourceStats = getDataSourceStats()
  const filteredCount = currentFilter === 'all' 
    ? parameters.length 
    : dataSourceStats[currentFilter] || 0

  const currentOption = DATA_SOURCE_OPTIONS.find(opt => opt.value === currentFilter)

  return (
    <div className={`space-y-3 ${className}`}>
      {/* 主筛选控件 */}
      <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
        <div className="flex items-center gap-3">
          <Filter className="h-4 w-4 text-gray-600" />
          <span className="font-medium text-sm">数据来源筛选:</span>
          
          <Select value={currentFilter} onValueChange={onFilterChange}>
            <SelectTrigger className="w-40">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {DATA_SOURCE_OPTIONS.map(option => (
                <SelectItem key={option.value} value={option.value}>
                  <div className="flex items-center gap-2">
                    <div className={`w-3 h-3 rounded-full ${option.color}`} />
                    <span>{option.label}</span>
                    {option.value !== 'all' && dataSourceStats[option.value] && (
                      <Badge variant="outline" className="ml-1 text-xs">
                        {dataSourceStats[option.value]}
                      </Badge>
                    )}
                  </div>
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        <div className="flex items-center gap-3">
          <span className="text-sm text-gray-600">
            显示 <span className="font-medium text-blue-600">{filteredCount}</span> / {parameters.length} 个字段
          </span>
          
          <Button
            variant="ghost"
            size="sm"
            onClick={() => setShowDetails(!showDetails)}
            className="flex items-center gap-1"
          >
            详情
            {showDetails ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
          </Button>
        </div>
      </div>

      {/* 快速筛选按钮 */}
      <div className="flex flex-wrap gap-2">
        {DATA_SOURCE_OPTIONS.map(option => (
          <Button
            key={option.value}
            variant={currentFilter === option.value ? "default" : "outline"}
            size="sm"
            onClick={() => onFilterChange(option.value)}
            className="flex items-center gap-2"
          >
            <div className={`w-2 h-2 rounded-full ${option.color}`} />
            {option.label}
            {option.value !== 'all' && dataSourceStats[option.value] && (
              <Badge variant="secondary" className="ml-1">
                {dataSourceStats[option.value]}
              </Badge>
            )}
          </Button>
        ))}
      </div>

      {/* 详细信息卡片 */}
      {showDetails && (
        <Card>
          <CardHeader>
            <CardTitle className="text-base flex items-center gap-2">
              <div className={`w-3 h-3 rounded-full ${currentOption?.color}`} />
              {currentOption?.label}
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <p className="text-sm text-gray-600">
              {currentOption?.description}
            </p>
            
            {/* 统计信息网格 */}
            <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
              {DATA_SOURCE_OPTIONS.slice(1).map(option => {
                const count = dataSourceStats[option.value] || 0
                const percentage = parameters.length > 0 ? Math.round((count / parameters.length) * 100) : 0
                
                return (
                  <div 
                    key={option.value}
                    className={`p-3 rounded-lg border-2 cursor-pointer transition-all ${
                      currentFilter === option.value 
                        ? 'border-blue-500 bg-blue-50' 
                        : 'border-gray-200 hover:border-gray-300'
                    }`}
                    onClick={() => onFilterChange(option.value)}
                  >
                    <div className="flex items-center gap-2 mb-1">
                      <div className={`w-3 h-3 rounded-full ${option.color}`} />
                      <span className="font-medium text-sm">{option.label}</span>
                    </div>
                    <div className="text-2xl font-bold text-gray-900">{count}</div>
                    <div className="text-xs text-gray-500">{percentage}% 的字段</div>
                  </div>
                )
              })}
            </div>

            {/* 数据来源说明 */}
            <div className="pt-3 border-t">
              <h4 className="font-medium text-sm mb-2">数据来源说明:</h4>
              <div className="space-y-1 text-xs text-gray-600">
                <div><strong>P (采购数据):</strong> 制造厂家、型号、技术参数</div>
                <div><strong>E (设计数据):</strong> 设备名称、规格等设计确定的参数</div>
                <div><strong>M (监测数据):</strong> 监测设备和系统提供的实时参数和状态</div>
                <div><strong>C (施工数据):</strong> 施工安装相关数据</div>
                <div><strong>O (建设数据):</strong> 建设过程中记录的参数和状态</div>
                <div><strong>R (运维数据):</strong> 运维过程中记录的参数和状态</div>
              </div>
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  )
}
